import cv2
import numpy as np

if __name__ == '__main__':
    # 1.图片输入
    image_np = cv2.imread('xingxing.jpg')
    # 2.灰度化处理
    image_np_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)
    # 3.二值化
    _, image_np_thresh = cv2.threshold(image_np_gray, 127, 255, cv2.THRESH_BINARY)
    #4. 查找轮廓
    contours, _ = cv2.findContours(image_np_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 准备 12 种不同颜色（BGR）
    color_list = [
        (0, 0, 255),       # 红
        (0, 128, 255),     # 橙
        (0, 255, 255),     # 黄
        (0, 255, 0),       # 绿
        (255, 255, 0),     # 青
        (255, 0, 0),       # 蓝
        (255, 0, 128),     # 紫
        (128, 0, 128),     # 洋红
        (255, 255, 255),   # 白
        (128, 128, 128),   # 灰
        (0, 0, 0),         # 黑
        (128, 255, 128)    # 浅绿
    ]

    contour_image = image_np.copy()
    for idx, cnt in enumerate(contours):
        rect = cv2.minAreaRect(cnt)
        points = cv2.boxPoints(rect)
        points = np.int32(points)

        color = color_list[idx % len(color_list)]   # 超过12个自动循环
        cv2.drawContours(contour_image, [points], -1, color, 2)

    cv2.imshow('contour_image', contour_image)
    cv2.imwrite('juxing.jpg', contour_image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()